from odoo import fields, models, api
from odoo.exceptions import UserError


class RPSequenceCode(models.Model):
    _name = 'rp.sequence.code'
    _description = 'RP序列号'
    _sql_constraints = [('unique_name', 'UNIQUE(code)', '名称必须唯一'),
                        ('unique_prefix', 'UNIQUE(model_id,prefix)', '同一个模型中，序列号必须唯一')]
    _rec_name = 'code'

    code = fields.Char(string='编号', default='RP_SQC/***', copy=False, index=True)
    model_id = fields.Many2one(string='关联模型', comodel_name='ir.model')

    prefix = fields.Char(string='前缀', required=True)
    index = fields.Integer(string='索引', default=1, required=True)
    padding = fields.Integer(string='位数(零填充)', default=3, required=True)

    key = fields.Char(string='键')
    value = fields.Char(string='值')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list: 
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.sequence.code') or '/'
        return super(RPSequenceCode, self).create(vals_list)

    def explore_sequence(self, model, prefix, key, padding=3):
        """ 每探索一次，相应记录 index +1 """
        model_rcd = self.env['ir.model'].search([('model', '=', model.replace('_', '.'))])
        rcd = self.search([('model_id', '=', model_rcd.id), ('prefix', '=', prefix)], limit=1)
        if not rcd:
            rcd = self.env['rp.sequence.code'].create([{'model_id': model_rcd.id,
                                                       'prefix': prefix,
                                                       'padding': padding,
                                                       'key': key}])
        print_code = rcd.prefix + '_' + rcd.key + '/' + str(rcd.index).zfill(rcd.padding)  # 先输出
        rcd.index = rcd.index + 1  # 再 +1
        return print_code
